package com.hsj.springai.config;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

// 第一步 资源类创建，
public class Share {
    public static void main(String[] args) {
        TransmittableThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();
        //通过jdk的工具类创建线程池
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        //用阿里的包  提供的工具类 对我们创建的线程池 包装一下
        threadPool = TtlExecutors.getTtlExecutorService(threadPool);
        //主线程设置threadLocal的值
        transmittableThreadLocal.set(Thread.currentThread().getName() + "123");
        //主线程获取 正常
        System.out.println(transmittableThreadLocal.get());
        threadPool.execute(() -> {
            //线程池的子线程获取正常
            System.out.println(transmittableThreadLocal.get());  //123
        });
        //修改threadLocal的值
        transmittableThreadLocal.set(Thread.currentThread().getName() + "456");
        threadPool.execute(() -> {
            //线 程池的子线程获取正常
            System.out.println(transmittableThreadLocal.get());  //456
        });
    }


    public static void finalOK_shutdownAndAwaitTermination(ExecutorService threadPool) {
        if (threadPool != null && !threadPool.isShutdown()) {
            threadPool.shutdown();
            try {
                if (!threadPool.awaitTermination(120, TimeUnit.SECONDS)) {
                    threadPool.shutdownNow();
                    if (!threadPool.awaitTermination(120, TimeUnit.SECONDS)) {
                        System.out.println("pool did not terminate");
                    }
                }
            } catch (InterruptedException e) {
                threadPool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }

}


